package com.shuan;

import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor {

    private static final String ALGORITHM = "AES";
    // 16/24/32字节密钥
    private static final String KEY = "your-16bytes-secret-key012345678";

    public static byte[] encrypt(byte[] originalBytes, byte[] key) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return cipher.doFinal(originalBytes);
    }

    // 可选：保留之前的文件加密方法（根据需求调整）
    public static void encryptClass(String className, byte[] key) throws Exception {
        // 读取原始类字节码
        Path path = Paths.get(ClassLoader.getSystemResource(className + ".class").toURI());
        byte[] originalBytes = Files.readAllBytes(path);
        byte[] encryptedBytes = encrypt(originalBytes, key);
        String outPath = path.toAbsolutePath().toString();
        try (FileOutputStream fos = new FileOutputStream(outPath.replace(".class", ".enc"))) {
            fos.write(encryptedBytes);
        }
    }

    public static void encryptClass(String className) throws Exception {
        // 读取原始类字节码
        Path path = Paths.get(ClassLoader.getSystemResource(className + ".class").toURI());

        byte[] originalBytes = Files.readAllBytes(path);

        // 加密
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes = cipher.doFinal(originalBytes);
        String outPath = path.toAbsolutePath().toString();
        // 写入加密文件（模拟加密后的存储）
        try (FileOutputStream fos = new FileOutputStream(outPath.replace(".class", ".enc"))) {
            fos.write(encryptedBytes);
        }
    }

    public static void main(String[] args) throws Exception {
        // 示例：加密 com.example.MyService 类
        //encryptClass("com/shuan/MyService");
    }
}
